package com.ds.lens.flink.monitor.eventsinkjob.function.notify.weixin;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ds.lens.data.common.document.dto.MonitorEvent;
import com.ds.lens.data.common.util.HttpServiceClient;
import com.ds.lens.flink.monitor.eventsinkjob.function.notify.MonitorEventNotifier;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;

/**
 * @author WeiShaoying
 * @date 2020/2/11 下午4:12
 */
@Slf4j
public class WeiXinMonitorEventNotifier implements MonitorEventNotifier<MonitorEvent, String> {

    private WeiXinConfig weiXinConfig;

    private WeiXinClient weiXinClient;

    public WeiXinMonitorEventNotifier(WeiXinConfig weiXinConfig) {
        this.weiXinConfig = weiXinConfig;
        this.weiXinClient = HttpServiceClient.getRestClient(WeiXinClient.class, weiXinConfig.getUrl(), false);
        this.weiXinConfig.setAccessToken(getToken());
    }

    @Override
    public String send(MonitorEvent data) throws Exception {
        WeiXinText weiXinText = new WeiXinText();
        weiXinText.setContent(data.getNotify().getContent());
        WeiXinContent content = new Gson().fromJson(data.getNotify().getChannelContent(), WeiXinContent.class);
        WeiXin weiXin = new WeiXin();
        if (ArrayUtils.isNotEmpty(content.getTouser())) {
            weiXin.setTouser(String.join("|", content.getTouser()));
        }
        if (ArrayUtils.isNotEmpty(content.getToparty())) {
            weiXin.setToparty(String.join("|", content.getToparty()));
        }
        if (ArrayUtils.isNotEmpty(content.getTotag())) {
            weiXin.setTotag(String.join("|", content.getTotag()));
        }
        weiXin.setMsgtype("text");
        weiXin.setText(weiXinText);
        weiXin.setAgentid(weiXinConfig.getAgentid());
        JsonObject jsonObject = weiXinClient.sendMsg(weiXinConfig.getAccessToken(), weiXin);
        int code = jsonObject.get("errcode").getAsInt();
        if (code != 0) {
            if (code == 42001 || code == 40014) {
                weiXinConfig.setAccessToken(getToken());
                weiXinClient.sendMsg(weiXinConfig.getAccessToken(), weiXin);
            } else {
                log.error("send weixin code:{}  error:{}", code, jsonObject.get("errmsg").getAsString());
            }
        }
        return null;
    }

    private String getToken() {
        return weiXinClient.getToken(weiXinConfig.getCorpid(), weiXinConfig.getCorpsecret()).get("access_token").getAsString();
    }
}
